﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Documents;
using System.Windows.Forms;
using WebAuto.DataModel;
using WebAutoUtils;
using WebAutomation;

namespace WebAuto
{
    static class Program
    {
        internal static class NativeMethods
        {
            [DllImport("kernel32.dll")]
            internal static extern Boolean AllocConsole();
        } 

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] arguments)
        {
            
            if (arguments.Count()>0)
            {
                NativeMethods.AllocConsole(); 
                string testLine = arguments[0];
                Console.WriteLine("******************Integration Tester v1.0.0*******************");
                Console.WriteLine("Started :" + DateTime.Now);
                Console.WriteLine("Running test :" + testLine+"...please wait...");
                Console.WriteLine("");
                Console.WriteLine("");


                using (new ErrorModeContext(ErrorModes.FailCriticalErrors | ErrorModes.NoGpFaultErrorBox | ErrorModes.Default))
                {

                    WebAutomation.WebAuto webAuto = new WebAutomation.WebAuto(testLine);
                    webAuto.RunTest(null, onTestRunComplete, null, null, false, null, General.GetExceptionRules());
                }

            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }

        private static void onTestRunComplete(Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>> TestResults, Thread thread)
        {
            string emailTestStatus = "";
            string emailErrorMessage = "";
            int iCount = 0;
            foreach (var items in TestResults)
            {
                bool isFailed = false;
                bool isFrameworkErr = false;
                string failErrorMessage = "";
                string frameworkErrorMessage = "";

                _testStatus(TestResults, ref isFailed, ref isFrameworkErr, ref failErrorMessage, ref frameworkErrorMessage, items.Key.TestFileName, items.Key.TestResultsFolder, items.Key.TestBrowser);
                Console.WriteLine("--------------------------------------------------------------------------------");
                string message = items.Key.TestName + " : Test PASSED";
                emailTestStatus = "Success";
                Console.ForegroundColor = ConsoleColor.Green;
                if (isFailed)
                {
                    emailTestStatus = "Failed";
                    emailErrorMessage = failErrorMessage;
                    Console.ForegroundColor = ConsoleColor.Red;
                    message = items.Key.TestName + " : Test FAILED." + failErrorMessage;
                }
                if (isFrameworkErr)
                {
                    emailTestStatus = "Error";
                    emailErrorMessage = frameworkErrorMessage;
                    Console.ForegroundColor = ConsoleColor.Magenta;
                    message = items.Key.TestName + " : Test ERROR." + frameworkErrorMessage;
                }

                string errorEmail = "";
                General.SendEmail("BunnyChow-Integration Tester " + Utils.GetVersionNumber() + " Console process", "BunnyChow-Integration Tester", items.Key.TestName, emailTestStatus, iCount, emailErrorMessage, items.Key.TestBrowser, ref errorEmail);

                Console.WriteLine(message);
                Console.ForegroundColor = ConsoleColor.Gray;
                
                var list = items.Value;
                var secToRun = 0.00;
                var name = "";
                var tmpName = "";
                foreach (var listItem in list.Where(i => i.Key > -1))
                {
                    foreach (var val in listItem.Value)
                    {

                        Console.WriteLine(val.LineCommand+":"+val.LineSubCommand+"("+val.LineParameter+") : "+val.LinePassed);
                    }


                }
                Console.WriteLine("--------------------------------------------------------------------------------");
                Console.WriteLine("");
                iCount++;
            }

            
            
            //Console.ReadLine();
            Thread.Sleep(5000);
            Application.Exit();
        }

        private static void _testStatus(Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>> TestResults, ref bool isFailed, ref bool isFrameworkErr, ref string failErrorMessage, ref string frameworkErrorMessage, string testName, string CurrentTestLocationRunning,string browser)
        {
            string status = "Passed";
            string errorMessage = "";
            foreach (var items in TestResults)
            {
                var list = items.Value;
                var secToRun = 0.00;
                var name = "";
                var tmpName = "";
                foreach (var listItem in list.Where(i => i.Key > -1))
                {
                    foreach (var val in listItem.Value)
                    {
                        
                        isFailed = !val.LinePassed;
                        failErrorMessage = val.LineMessage;
                        errorMessage = failErrorMessage;
                        if(isFailed)
                        {
                            status = "Failed";
                        }
                        if (isFailed)
                        {

                            break;
                        }

                    }

                    if (isFailed)
                    {

                        break;
                    }

                }

                if (isFailed)
                {

                    break;
                }

            }


            
            string resultFolderLocation = "";
            foreach (var items in TestResults)
            {
                var list = items.Value;
                var secToRun = 0.00;
                var name = "";
                var tmpName = "";
                foreach (var listItem in list.Where(i => i.Key > -1))
                {
                    foreach (var val in listItem.Value)
                    {
                        isFrameworkErr = val.IsFrameworkError;
                        frameworkErrorMessage = val.LineMessage;
                        resultFolderLocation = val.ResultsFolderLocation;
                        errorMessage = frameworkErrorMessage;
                        if (isFrameworkErr)
                        {
                            status = "Error";
                        }
                        if (isFrameworkErr)
                        {

                            break;
                        }

                    }

                    if (isFrameworkErr)
                    {

                        break;
                    }

                }

                if (isFrameworkErr)
                {

                    break;
                }

            }

            Data data = new Data();
            DateTime dateRun = DateTime.Now;
            if (status == "Failed" || status == "Error")
            {
                resultFolderLocation = resultFolderLocation + "_Failed";
            }
            data.SaveTestRun(testName, testName, CurrentTestLocationRunning, dateRun, status, errorMessage, resultFolderLocation, browser);
            data = null;

        }
    }
}
